package com.aqielife.demo;



import com.aqielife.demo.entity.User;
import com.aqielife.demo.interfaces.IUserApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/rest")
public class UserController {
    @Autowired
    private IUserApi userApi;

    // 直接调用，实现调用rest接口效果
    @GetMapping("/")
    public Flux<User> getAll(){
        Flux<User> users = userApi.getAllUser();
        // 打印
        users.subscribe(System.out::print);
        return users;
    }

    /**
     * todo  catch exception: java.lang.RuntimeException: Not Found
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public Mono<ResponseEntity<User>> findOne(@PathVariable("id") String id){
        return userApi.getUserById(id)
                .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PostMapping("/user/")
    public Mono<ResponseEntity<User>> createOne(@RequestBody Mono<User> user){
        return userApi.createUser(user)
                .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @DeleteMapping("/user/{id}")
    public Mono<ResponseEntity<Object>> deleteOne(@PathVariable("id") String id){
        return userApi.deleteUserById(id)
                .map(u -> new ResponseEntity<>(HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));

    }
}
